<?php
/**
 * Created by PhpStorm.
 * User: yangkan
 * Date: 18-4-9
 * Time: 上午12:04
 */
set_time_limit(0);
include_once dirname(dirname(dirname(__FILE__)))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load_old("nn_logic/medium/medium_library_disk_logic.class.php");
\ns_core\m_load::load_old("nn_logic/medium/medium_library_cp_logic.class.php");
\ns_core\m_load::load_old("nn_logic/medium/medium_library_asset_logic.class.php");
\ns_core\m_load::load_old("nn_logic/medium/medium_library_filter_extension.class.php");
\ns_core\m_load::load("ns_core.m_medium");
class medium_analyze_file
{
    private $obj_dc = null;

    private $timer_path = '';

    private $child_path = '';

    private $arr_disk_list = null;

    private $str_dir_path  = '';

    /**
     * 默认构造函数
     */
    public function __construct()
    {
        $this->obj_dc = m_config::get_dc();
        $this->obj_redis_dc = m_config::get_redis_dc();
        $this->timer_path = m_config::return_child_path(__FILE__);
        //导出文件保存路径
        $this->str_dir_path  = dirname(dirname(dirname(dirname(__FILE__)))) . '/data/medium/';
    }

    /**
     * 分析文件基本信息
     */
    public function init($str_file_path)
    {
        if(!file_exists($str_file_path))
        {
            return false;
        }
        //查询磁盘ID
        $str_disk_id = '';
        $arr_dir_name = pathinfo($str_file_path);
        if(is_array($arr_dir_name) && isset($arr_dir_name['dirname']))
        {
            $arr_disk_id = explode('/',$arr_dir_name['dirname']);
            if(is_array($arr_disk_id) && !empty($arr_disk_id))
            {
                $str_disk_id = array_pop($arr_disk_id);
            }
        }
        if(empty($str_disk_id))
        {
            m_config::timer_write_log($this->timer_path,'查询服务器磁盘信息失败。磁盘ID：' . $str_disk_id,$this->child_path);
            return false;
        }
        //查询磁盘信息
        if(!isset($this->arr_disk_list[$str_disk_id]))
        {
            //查询磁盘信息
            $arr_disk_info = medium_library_disk_logic::query_one($this->obj_dc,array('nns_id' => $str_disk_id));
            if($arr_disk_info['ret'] != 0 || empty($arr_disk_info['data_info']))
            {
                m_config::timer_write_log($this->timer_path,'查询服务器磁盘信息失败。磁盘ID：' . $str_disk_id,$this->child_path);
                return false;
            }
            else
            {
                $this->arr_disk_list[$str_disk_id] = $arr_disk_info['data_info'];
            }
        }
        //获取允许的文件格式
        $this->get_file_format();
        //解析文件
        $arr_file_info = m_medium::analyze_file($str_file_path,$this->arr_disk_list[$str_disk_id]['nns_disk_path']);
        //     	echo '解析文件：【' . $str_file_path . '】';
        if($arr_file_info['ret'] != 0)
        {
            return false;
        }
// 	    echo "磁盘信息：" . var_export($this->arr_disk_list,true);
        //查询磁盘信息
        if($arr_file_info['ret'] == 0)
        {
            //正确数据
            $arr_right_data = $arr_file_info['data_info']['right_data'];
            $this->_handle_right_data($arr_right_data,$this->arr_disk_list[$str_disk_id]);

            //错误数据
            $arr_error_data = $arr_file_info['data_info']['error_data'];
            $this->_handle_error_data($arr_error_data,$this->arr_disk_list[$str_disk_id]);
        }
        return true;
    }
    
    public function init_v2($media_path_info,$str_disk_id)
    {
        $media_path_info = base64_decode($media_path_info);
        if(empty($str_disk_id))
        {
            m_config::timer_write_log($this->timer_path,'查询服务器磁盘信息失败。磁盘ID：' . $str_disk_id,$this->child_path);
            return false;
        }
        //查询磁盘信息
        if(!isset($this->arr_disk_list[$str_disk_id]))
        {
            //查询磁盘信息
            $arr_disk_info = medium_library_disk_logic::query_one($this->obj_dc,array('nns_id' => $str_disk_id));
            if($arr_disk_info['ret'] != 0 || empty($arr_disk_info['data_info']))
            {
                m_config::timer_write_log($this->timer_path,'查询服务器磁盘信息失败。磁盘ID：' . $str_disk_id,$this->child_path);
                return false;
            }
            else
            {
                $this->arr_disk_list[$str_disk_id] = $arr_disk_info['data_info'];
            }
        }
        //获取允许的文件格式
        $this->get_file_format();
        //解析文件
        $arr_file_info = m_medium::analyze_medium_file($media_path_info,$this->arr_disk_list[$str_disk_id]['nns_disk_path']);
        //     	echo '解析文件：【' . $str_file_path . '】';
        if($arr_file_info['ret'] != 0)
        {
            return false;
        }
// 	    echo "磁盘信息：" . var_export($arr_file_info,true);die;
        //查询磁盘信息
        if($arr_file_info['ret'] == 0)
        {
            //正确数据
            $arr_right_data = $arr_file_info['data_info']['right_data'];
            $this->_handle_right_data($arr_right_data,$this->arr_disk_list[$str_disk_id]);
        }
        return true;
    }
    
    /**
     * 获取允许的文件格式
     * @return boolean
     */
    public function get_file_format()
    {
        $result_file_format = nl_medium_library_filter_extension::query_all($this->obj_dc,0);
        if($result_file_format['ret'] !=0)
        {
            m_config::timer_write_log($this->timer_path,'查询文件后缀过滤条件失败：' . var_export($result_file_format,true),$this->child_path);
            return false;
        }
        $result_file_format = isset($result_file_format['data_info']) ? $result_file_format['data_info'] : null;
        $arr_file_format = null;
        if(is_array($result_file_format) && !empty($result_file_format))
        {
            foreach ($result_file_format as $value_format)
            {
                $arr_file_format[] = $value_format['nns_extension'];
            }
        }
        if(is_array($arr_file_format) && !empty($arr_file_format))
        {
            m_medium::$arr_file_format = $arr_file_format;
        }
        return true;
    }

    /**
     * 正确数据处理
     */
    private function _handle_right_data($arr_right_data,$arr_disk_info)
    {
        //参数验证
        if(!is_array($arr_right_data) || empty($arr_right_data))
        {
            return false;
        }
        //CP 信息处理
        if(isset($arr_right_data['cp_data']) && is_array($arr_right_data['media_data']) && !empty($arr_right_data['cp_data']))
        {
            foreach($arr_right_data['cp_data'] as $k_cp => $cp)
            {
                $result_exsist = medium_library_cp_logic::query_one($this->obj_dc, array('nns_id'=>$k_cp));
                if(isset($result_exsist['data_info']) && is_array($result_exsist['data_info']) && !empty($result_exsist['data_info']))
                {
                    continue;
                }
                medium_library_cp_logic::add($this->obj_dc, array(
                    'nns_id'               => $k_cp,
                    'nns_cp_name'          => $cp,
                    'nns_contactor'        => '',
                    'nns_telephone'        => '',
                    'nns_email'            => '',
                    'nns_addr'             => '',
                    'nns_cp_summary'       => '',
                    'nns_image_h'          => '',
                    'nns_image_v'          => '',
                    'nns_image_s'          => '',
                ));
            }
        }
        //文件处理
        if(isset($arr_right_data['media_data']) && is_array($arr_right_data['media_data']) && !empty($arr_right_data['media_data']))
        {
            $arr_asset_id = array();
            foreach($arr_right_data['media_data'] as $data)
            {
                if(!isset($data['asset_id']) || strlen($data['asset_id']) <1 || !isset($data['id']) || strlen($data['id']) <1)
                {
                    continue;
                }
                if(!in_array($data['asset_id'], $arr_asset_id))
                {
                    $arr_asset_id[] = $data['asset_id'];
                    //分类处理
                    $result_exsist = medium_library_asset_logic::query_one($this->obj_dc, array('nns_id'=>$data['asset_id'],'nns_cp_id'=>$data['cp_id'],'nns_disk_id'=>$arr_disk_info['nns_id']));
                    if(!isset($result_exsist['data_info']) || !is_array($result_exsist['data_info']) || empty($result_exsist['data_info']))
                    {
                        $arr_replace_asset = medium_library_asset_logic::add($this->obj_dc,array(
                            'nns_id'             => $data['asset_id'],
                            'nns_cp_id'          => $data['cp_id'],
                            'nns_disk_id'        => $arr_disk_info['nns_id'],
                            'nns_asset_name'     => $data['asset_name'],
                            'nns_asset_path'     => $data['asset_path_name'],
                            'nns_asset_type'     => isset($data['index']) && $data['index'] > 0 ? 1 : 0,
                            'nns_asset_summary'  => '',
                        ));
                        if($arr_replace_asset['ret'] !=0)
                        {
                            return false;
                        }
                    }
                }
                //文件处理
                $result_exsist = medium_library_file_logic::query_one($this->obj_dc, array('nns_id'=>$data['id']));
                if(isset($result_exsist['data_info']) && is_array($result_exsist['data_info']) && !empty($result_exsist['data_info']))
                {
                    continue;
                }
                medium_library_file_logic::add($this->obj_dc,array(
                    'nns_id'          => $data['id'],
                    'nns_cp_id'       => $data['cp_id'],
                    'nns_disk_id'     => $arr_disk_info['nns_id'],
                    'nns_asset_id'    => $data['asset_id'],
                    'nns_file_index'  => isset($data['index']) && strlen($data['index']) > 0 ? $data['index'] : 0,
                    'nns_file_name'   => $data['filename'],
                    'nns_file_url'    => (strtolower(substr(php_uname(), 0, 7)) == "windows") ? ltrim($data['url']) : '/' . ltrim($data['url'],'/'),
                    'nns_file_size'   => 0,
                    'nns_file_duration'   => 0,
                    'nns_general_fomart'   => '',
                    'nns_general_bit_rate_mode'   => '',
                    'nns_videos_kbps'   => 0,
                    'nns_videos_format'   => '',
                    'nns_videos_bit_rate_mode'   => '',
                    'nns_audios_kbps'   => 0,
                    'nns_audios_format'   => '',
                    'nns_audios_bit_rate_mode'   => '',                        
                    'nns_file_type'   => $data['extension'],
                    'nns_ext_url'     => '',
                    'nns_base_info'   => '',
                    'nns_is_analysis' => 0,
                    'nns_state'       => isset($data['index_state']) && strlen($data['index']) > 0 ? $data['index_state'] : 0,
                    'nns_again'       => 0,
                ));
            }
        }
        return true;
    }

    /**
     * 错误数据处理
     */
    private function _handle_error_data($arr_error_data,$arr_disk_info)
    {
        //参数验证
        if(!is_array($arr_error_data) || empty($arr_error_data))
        {
            return false;
        }
        //遍历错误文件入库
        $str_error_name = '';
        foreach($arr_error_data as $data)
        {
            if(!is_file($data)) continue;
            $str_error_name = pathinfo($data);
            $result_exsist = medium_library_file_logic::query_one($this->obj_dc, array('nns_id'=>md5($data)));
            if(isset($result_exsist['data_info']) && is_array($result_exsist['data_info']) && !empty($result_exsist['data_info']))
            {
                continue;
            }
            medium_library_file_logic::replace($this->obj_dc,array(
                'nns_id'          => md5($data),
                'nns_cp_id'       => '',
                'nns_disk_id'     => $arr_disk_info['nns_id'],
                'nns_asset_id'    => '',
                'nns_asset_type'  => '',
                'nns_file_index'  => 0,
                'nns_file_name'   => $str_error_name['filename'],
                'nns_file_url'    => $data,
                'nns_file_size'   => 0,
                'nns_file_duration'   => 0,
                'nns_general_fomart'   => '',
                'nns_general_bit_rate_mode'   => '',
                'nns_videos_kbps'   => 0,
                'nns_videos_format'   => '',
                'nns_videos_bit_rate_mode'   => '',
                'nns_audios_kbps'   => 0,
                'nns_audios_format'   => '',
                'nns_audios_bit_rate_mode'   => '',
                'nns_file_type'   => $str_error_name['extension'],
                'nns_ext_url'     => '',
                'nns_base_info'   => '',
                'nns_is_analysis' => 2,
                'nns_state'       => 1,
                'nns_again'       => 0,
            ));
        }
        return true;
    }
}
echo '文件地址：【' . $_SERVER['argv'][1] . '】地址结束';
if(isset($_SERVER['argv'][1]) && !empty($_SERVER['argv'][1]))
{
    $obj_medium_analyze_file = new medium_analyze_file();
    $obj_medium_analyze_file->init($_SERVER['argv'][1]);
}
else if(isset($_REQUEST['action']) && $_REQUEST['action']== 'bg_upload')
{
    $obj_medium_analyze_file = new medium_analyze_file();
    $result = $obj_medium_analyze_file->init_v2($_REQUEST['url'],$_REQUEST['diskid']);
    ob_clean();
    echo $result ? json_encode(array('ret'=>0,)) : json_encode(array('ret'=>1,));die;
}